package com.gitee.huanminabc.utils_tools.web_base.config;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONWriter;
import com.alibaba.fastjson.serializer.SerializeFilter;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.gitee.huanminabc.nullchain.common.NullResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

//通用接口返回值处理
@ControllerAdvice
@Slf4j
public class BaseResponseBodyHandleConfig implements ResponseBodyAdvice<Object> {
    @Override
    public boolean supports(MethodParameter returnType, Class<? extends HttpMessageConverter<?>> converterType) {
        /*支持所有方法*/
        return true;
    }
    //所有接口返回信息都会从这里出去,我们可以在这里进行一些特殊处理,或者日志记录
    @Override
    public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType, Class<? extends HttpMessageConverter<?>> selectedConverterType, ServerHttpRequest request, ServerHttpResponse response) {
        if (NullResult.class.isAssignableFrom(returnType.getParameterType())) {
            String responseBody = JSON.toJSONString(body, SerializerFeature.PrettyFormat, SerializerFeature.IgnoreNonFieldGetter);
            //限制返回值长度1024
            if (responseBody.length() > 1024) {
                responseBody = responseBody.substring(0, 1024)+"......内容被截断";
            }
            log.info("{}方法返回值:{}",request.getURI().getPath(), responseBody ); //WriteMapNullValue:输出空置字段
            return body;
        }else{
            return body;
        }
    }




}
